<?php
namespace App\Models\Bureau;

use App\Models\User\WxUser;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

class WxClubTeam extends Model
{
    use HasDateTimeFormatter;

    protected $table = 'wx_club_team';

    protected static function boot()
    {
        parent::boot();

        static::updating(function ($model) {
            if (array_key_exists('members', $model->attributes)) {
                $model->attributes['members'] = $model->processMembersAttribute($model->attributes['members']);
            }
        });
    }

    public function getMembersAttribute($value)
    {
        return array_map(function ($v) {
            return (int)$v;
        }, _empty_default_(json_decode(str_replace("'", '"', _empty_default_($value, '[]')), true), []));
    }

    public function setMembersAttribute($value)
    {
        $this->attributes['members'] = $this->processMembersAttribute($value);
    }

    protected function processMembersAttribute($value)
    {
        if (is_array($value) && count($value) > 0) {
            $arr = array_map(function ($v) {
                return (int)$v;
            }, $value);

            $str = "";
            foreach ($arr as $num) {
                $str .= (",'".$num."'");
            }
            return '[' . ltrim($str, ',') . ']';
        }else if(is_string($value) && strpos($value, '[') === 0){
            return $value;
        } else {
            return null;
        }
    }

}
